import redis
import configparser
import os
import logging

logger = logging.getLogger(__name__)

class RedisClient:
    def __init__(self, config_file='config.ini'):
        self.config_file = config_file
        self.client = self._connect()

    def _connect(self):
        config = configparser.ConfigParser()
        if not os.path.exists(self.config_file):
            logger.error(f"❌ 配置文件 {self.config_file} 不存在")
            return None

        try:
            config.read(self.config_file, encoding='utf-8')
            redis_config = {
                'host': config.get('Redis', 'host'),
                'port': int(config.get('Redis', 'port')),
                'db': int(config.get('Redis', 'db')),
                'password': config.get('Redis', 'password', fallback=None)
            }

            client = redis.StrictRedis(**redis_config, decode_responses=True)
            client.ping()  # 测试连接
            logger.info("🔌 成功连接到 Redis")
            return client
        except Exception as e:
            logger.error(f"❌ Redis 连接失败：{str(e)}", exc_info=True)
            return None

    def set_token(self, key='auth_token', token=None, expire=3600):
        """将 token 存入 Redis，并设置过期时间"""
        if not self.client or not token:
            logger.warning("🚫 无法写入 Redis：连接未建立或 token 为空")
            return False
        try:
            self.client.setex(key, expire, token)
            logger.info("💾 Token 已写入 Redis")
            return True
        except Exception as e:
            logger.error(f"❌ 写入 Redis 失败：{str(e)}", exc_info=True)
            return False

    def get_token(self, key='auth_token'):
        """从 Redis 获取 token"""
        if not self.client:
            logger.warning("🚫 无法读取 Redis：连接未建立")
            return None
        try:
            return self.client.get(key)
        except Exception as e:
            logger.error(f"❌ 读取 Redis 失败：{str(e)}", exc_info=True)
            return None